package com.jesper.seckill.service.impl;

import cn.hutool.core.util.StrUtil;
import com.code.starter.util.RedisUtils;
import com.jesper.seckill.constant.RedisKeyPrefix;
import com.jesper.seckill.entity.po.User;
import com.jesper.seckill.mapper.UserMapper;
import com.jesper.seckill.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jesper.seckill.util.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  登录相关处理类
 * </p>
 *
 * @author sjw
 * @since 2024-01-18
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    //token过期时间
    private static final Integer TOKEN_EXPIRE_DAYS = 5;
    //token续期时间
    private static final Integer TOKEN_RENEWAL_DAYS = 2;

    @Autowired
    private TokenUtil tokenUtil;

    @Override
    public boolean verify(String token) {
        Long uid = tokenUtil.getUidOrNull(token);//用户id
        if (Objects.isNull(uid)){
            return false;
        }
        String key = RedisKeyPrefix.getKey(RedisKeyPrefix.USER_TOKEN_STRING, uid);
        //从redis中获取对应token信息
        String realToken = RedisUtils.getStr(key);
        return Objects.equals(token,realToken);
    }

    @Async
    @Override
    public void renewalTokenIfNecessary(String token) {
        Long uid = tokenUtil.getUidOrNull(token);
        if (Objects.isNull(uid)){
            return;
        }
        String key = RedisKeyPrefix.getKey(RedisKeyPrefix.USER_TOKEN_STRING, uid);
        long expireDays = RedisUtils.getExpire(key, TimeUnit.DAYS);
        if (expireDays == -2){
            //不存在的key
            return;
        }
        if (expireDays < TOKEN_RENEWAL_DAYS){//小于一天的token帮忙续期
            RedisUtils.expire(key,TOKEN_EXPIRE_DAYS,TimeUnit.DAYS);
        }
    }

    @Override
    public String login(Long uid) {
        String key = RedisKeyPrefix.getKey(RedisKeyPrefix.USER_TOKEN_STRING, uid);
        String token = RedisUtils.getStr(key);
        if (StrUtil.isNotBlank(token)){
            return token;
        }
        //获取用户token
        token = tokenUtil.createToken(uid);
        //token过期用redis中心化控制，初期采用5天过期，剩余1天自动续期的方案。后续可以使用双token实现
        RedisUtils.set(key,token,TOKEN_RENEWAL_DAYS, TimeUnit.DAYS);
        return token;
    }

    @Override
    public Long getValidUid(String token) {
        boolean verify = verify(token);
        return verify ? tokenUtil.getUidOrNull(token) : null;
    }
}
